package com.tuanzi.loan.web.bean.templateConf;

import com.tuanzi.loan.business.entity.templateConf.LoanApiModelItemOptionbasisEntity;
import com.tuanzi.loan.business.service.templateConf.TemplateItemOptionService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.templateConf.TemplateItemOptionRequest;
import com.tuanzi.loan.vo.response.templateConf.TemplateItemOptionResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang.math.NumberUtils;
import org.primefaces.event.RowEditEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

/**
 * 资料填写模板项配置
 */
@Debug
@Component
@ViewScoped
@Data
@EqualsAndHashCode(callSuper = true)
public class TemplateItemOptionListBean extends JSFListingBean<TemplateItemOptionRequest, TemplateItemOptionResponse> {

    private static final long serialVersionUID = -7456998959122405455L;

    @Autowired
    private TemplateItemOptionService templateItemOptionService;

    private List<LoanApiModelItemOptionbasisEntity> itemOptionList;

    @PostConstruct
    private void init() {
        initLazyDataModel();
    }

    private void initLazyDataModel() {
        String itembasisId = getParamFromRequest("id");
        itemOptionList = templateItemOptionService.findByItembasisId(NumberUtils.toLong(itembasisId));
    }

    //编辑行
    public void onRowEdit(RowEditEvent event) {
        LoanApiModelItemOptionbasisEntity entity = (LoanApiModelItemOptionbasisEntity) event.getObject();
        templateItemOptionService.saveOrUpdate(entity);
        addSuccessfullyMessage();
    }

    //删除行
    public void onRowCancel(RowEditEvent event) {
        LoanApiModelItemOptionbasisEntity entity = (LoanApiModelItemOptionbasisEntity) event.getObject();
        if (entity.getId() != null) {
            templateItemOptionService.delete(entity.getId());
        }
        itemOptionList.remove(entity);
        addSuccessfullyMessage();
    }

    //新增一行
    public void onAddNew(Long itembasisId) {
        LoanApiModelItemOptionbasisEntity entity = new LoanApiModelItemOptionbasisEntity();
        entity.setId(null);
        entity.setItembasisId(itembasisId);
        itemOptionList.add(entity);
        addSuccessfullyMessage();
    }

}
